from socketserver import TCPServer, StreamRequestHandler
import numpy as np
import random as rd
from pylab import *
import re

NN = 200*3

patch = 0
data = {}
data['Temp'] = []
data['RH'] = []
norm_pos = 0

xx = np.linspace(1, 100000, 100000)

pro_data = {}
pro_data['ir_r'] = np.zeros(NN)
pro_data['ir_p'] = np.zeros(NN)
pro_data['ir_d'] = np.zeros(NN)
pro_data['ir_d2'] = np.zeros(NN)
pro_data['temp_r'] = np.zeros(NN)
data_ptr = {}
data_ptr['ir_r'] = 0
data_ptr['ir_p'] = 0
data_ptr['ir_d'] = 0
data_ptr['ir_d2'] = 0
data_ptr['temp_r'] = 0

fig = figure(figsize=(8, 5))
ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(234)
ax4 = fig.add_subplot(235)
ax_temp = fig.add_subplot(133)

pat1 = re.compile(r'(.*)%,(.*)℃')


class Handler(StreamRequestHandler):
    def handle(self):
        addr = self.request.getpeername()
        print('Got connection from', addr)
        self.wfile.write(b'Thank you for connecting')
        global patch, pat1, data
        patch += 1
        print('\x1b[2J')  # clear

        ion()
        # Create a figure and a set of subplots.
        #fig, ax = subplots(figsize=(8, 5))

        # figure,ax=plt.subplots()
        # lines,=ax.plot([],[])
        # ax.set_autoscaley_on(True)
        #ax1.title("Data from"+str(addr))

        global ax_temp
        ax_temp.grid()
        ax_temp.set_xlabel(r'$Time$')
        ax_temp.set_ylabel(r'$Value( ^{o}C)$')
        ax_temp.set_title(r'$Temprature$')

        while 1:
            imfor = self.rfile.readline().decode().strip()
            # imfor=self.rfile.read(length).decode()
            print(imfor)
            if imfor == "data":
                self.norm_display(imfor)
            elif imfor in ['ir_r', 'ir_p', 'ir_d', 'ir_d2']:
                print("##access the debug##")
                # cla()
                # close()
                self.debug_display(imfor)
                self.wfile.write(b'end')
                # show()
            elif imfor in ['temp_r']:
                self.temp_display(imfor)
                self.wfile.write(b'end')

            # print('\x1b[1;1H'+"{}:{}".format(i,imfor))#,end='')

    def norm_display(self, imfor):
        mt = pat1.match(imfor)
        if mt == None:
            print("info:{}".format(imfor))
        else:
            global ax_temp
            norm_pos += 1
            '''print(imfor)
            print(mt)
            print(type(mt))'''
            RH = float(mt.group(1))
            T = float(mt.group(2))
            print("{}:{}###{:.5f}%,{:.5f}℃".format(norm_pos, imfor, RH, T))
            data['RH'].append(RH)
            data['Temp'].append(T)

            # subplot(231)
            ax_temp.set_xlim(1, norm_pos)
            ax_temp.set_ylim(min(data['Temp'])-0.001, max(data['Temp'])+0.001)
            '''lines.set_xdata(xx[0:i-1])
            lines.set_ydata(yy[0:i-1])
            lines.set_color('k')
            lines.set_linewidth(0.7)
            ax.relim()
            ax.autoscale_view()'''
            # figure.canvas.draw()
            # figure.canvas.flush_events()
            ax_temp.plot(xx[1:norm_pos], data['Temp'][0:norm_pos-1], 'k', linewidth=0.7)
    pass

    def debug_display(self, tag):
        while True:
            try:
                temp = self.rfile.readline().decode().strip()
                len = int(temp)
                print(temp)
                break
            except ValueError:
                print("Error : "+temp)
        # len=int(self.rfile.readline().decode().strip())
        for i in range(0, len):
            while True:
                try:
                    temp = int(
                        self.rfile.readline().decode().strip())
                    print(tag, ' # ', i, '/', len, ' : ', temp)
                    break
                except ValueError:
                    print("Error : "+temp)
            pro_data[tag][data_ptr[tag]] = temp
            data_ptr[tag] += 1
            if data_ptr[tag] >= NN:
                data_ptr[tag]-=NN
        global ax1, ax2, ax3, ax4
        if tag == 'ir_r':
            ax = ax1
        elif tag == 'ir_p':
            ax = ax2  # subplot(232)
        elif tag == 'ir_d':
            ax = ax3  # subplot(233)
        elif tag == 'ir_d2':
            ax = ax4  # subplot(234)
        else:
            pass
        ax.cla()
        ax.grid()
        # ax.set_xlabel(r'$Time$')
        # ax.set_ylabel(r'$Value$')
        # ax.set_title(r'${{}}$'.format(tag))
        ax.set_xlim(1, NN)
        ax.set_ylim(min(pro_data[tag])-30, max(pro_data[tag])+30)
        ax.plot(xx[0:NN], np.concatenate([pro_data[tag][data_ptr[tag]:NN], pro_data[tag][0:data_ptr[tag]]]), 'k', linewidth=0.7)
        pause(0.1)

    def temp_display(self, tag):
        while True:
            try:
                temp = self.rfile.readline().decode().strip()
                len = int(temp)
                print(temp)
                break
            except ValueError:
                print("Error : "+temp)
        # len=int(self.rfile.readline().decode().strip())
        for i in range(0, len):
            while True:
                try:
                    temp = double(
                        self.rfile.readline().decode().strip())
                    print(tag, ' # ', i, '/', len, ' : ', temp)
                    break
                except ValueError:
                    print("Error : "+temp)
            pro_data[tag][data_ptr[tag]] = temp
            data_ptr[tag] += 1
            if data_ptr[tag] >= NN:
                data_ptr[tag]-=NN
        global ax_temp
        if tag == 'temp_r':
            ax = ax_temp
        ax.cla()
        ax.grid()
        # ax.set_xlabel(r'$Time$')
        # ax.set_ylabel(r'$Value$')
        # ax.set_title(r'${{}}$'.format(tag))
        ax.set_xlim(1, NN)
        ax.set_ylim(min(pro_data[tag])-0.01, max(pro_data[tag])+0.01)
        ax.plot(xx[0:NN], np.concatenate([pro_data[tag][data_ptr[tag]:NN], pro_data[tag][0:data_ptr[tag]]]), 'k', linewidth=0.7)


server = TCPServer(('', 6666), Handler)
server.serve_forever()
